import '@wangeditor/editor/dist/css/style.css' // 引入 css

import React, { useState, useEffect } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';

import { uploadFile } from "../../api/upload"



type InsertFnType = (url: string, poster: string) => void


const MyEditor = (props: any) => {
    const { value, onChange } = props;
    // editor 实例
    const [editor, setEditor] = useState<IDomEditor | null>(null)
console.log(value)
    // 编辑器内容
    // const [html, setHtml] = useState<string>()

    // 工具栏配置
    const toolbarConfig: Partial<IToolbarConfig> = {}

    // 编辑器配置
    const editorConfig: Partial<IEditorConfig> = {
        placeholder: '请输入内容...',
        MENU_CONF: {
            uploadImage: {
                base64LimitSize: 5 * 1024,
                async customUpload(file: File, insertFn: InsertFnType) {
                   await uploadFile(file).then((res)=>{
                    if (res.code===0) {
                        insertFn(res.data as string,res.data as string)
                    }
                   }) 
                }
            },
            // uploadVideo: {
            //     server: '/api/upload',
            //     async customUpload(file, insertFn) {
            //         if (isLoading) return message.error('上传凭据获取中，请稍后再试')
            //         message.loading('上传中...')
            //         const { data } = await uploadFile({
            //             file: file,
            //             typeName: "富文本上传视频",
            //             uploadToken: uploadToken
            //         }).catch(err => {
            //             message.error('上传失败')
            //         }).finally(() => {
            //             message.destroy()
            //         })
            //         if (data) insertFn(data.src)
            //     }
            // }
        }

    }

    // 及时销毁 editor ，重要！
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])

    return (
        <>
            <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
                <Toolbar
                    editor={editor}
                    defaultConfig={toolbarConfig}
                    mode="default"
                    style={{ borderBottom: '1px solid #ccc' }}
                />
                <Editor
                    defaultConfig={editorConfig}
                    value={value}
                    onCreated={setEditor}
                    onChange={editor => { onChange(editor.getHtml()) }}
                    mode="default"
                    style={{ height: '300px', overflowY: 'hidden' }}
                />
            </div>
            {/* <div style={{ marginTop: '15px' }}>
                {html}
            </div> */}
        </>
    )
}

export default MyEditor